﻿using Microsoft.AspNetCore.Mvc;
using Snowflake;
using Step4.Unit4.ModelBinding.Models;
using System.Net.Http.Headers;

namespace Step4.Unit4.ModelBinding.Controllers
{
    public class ProductController : Controller
    {
        private readonly IdWorker _idWorker;
        private readonly IWebHostEnvironment _webHostEnvironment;  // 此服务在应用启动时就被放入IOC容器了

        public ProductController(IWebHostEnvironment webHostEnvironment)
        {
            _idWorker = SnowflakeUtil.CreateIdWorker(); // 静态类，没有接口，不能注入
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public IActionResult Submit(ProductInput input)
        {
            // 文件重命名
            var fileName = _idWorker.NextId() + "." + Path.GetExtension(input.ProductImage.FileName);// 使用雪花算法重命名文件，方式文件名重复 
            // 获取存储路径
            var filePath = Path.Combine(_webHostEnvironment.ContentRootPath, "upload", fileName);// ContentRootPath 是项目根目， WebRootPath是wwwroot
            using FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            input.ProductImage.CopyTo(fileStream); // 每次从文件流中拿80k,知道所有的字节流都被拷贝完成
            return Ok("上传成功！");
        }

        /// <summary>
        /// 只绑定指定的属性，(默认情况下绑定所有的属性)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Submit2([Bind("Price", "ProductCategory")] ProductInput input)
        {


            return Ok("指定属性绑定成功！");
        }
    }
}
